﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Drawing;
using SlimDX;
using SlimDX.Direct2D;
using System.IO;

namespace GaugeEngine.Graphics
{
    public class GraphicsManager : GameComponent, IDisposable
    {
        private Painter m_painter;

        public int Height = 480;
        public int Width = 640;

        WindowRenderTarget w;
        SlimDX.Direct2D.Brush b;
        Factory f;

        public GraphicsManager(Game g)
            : base(g)
        {
            f = new Factory(FactoryType.SingleThreaded);
            WindowRenderTargetProperties wrtp = new WindowRenderTargetProperties()
            {
                Handle = g.GameForm.Handle,
                PixelSize = new Size(800,600),
                PresentOptions = PresentOptions.None
            };
            w = new WindowRenderTarget(f, wrtp);
            b = new SolidColorBrush(w, Color.Red);  

            w.AntialiasMode = AntialiasMode.PerPrimitive;

            m_painter = new Painter(w);

        }

        public static SlimDX.Direct2D.Bitmap LoadBitmap(RenderTarget rt, System.Drawing.Bitmap sysbit)
        {
            SlimDX.Direct2D.Bitmap result = null;

            System.Drawing.Imaging.BitmapData bitData = sysbit.LockBits(new Rectangle(0, 0, sysbit.Width, sysbit.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

            DataStream dataStream = new DataStream(bitData.Scan0, bitData.Stride * bitData.Height, true, false);

            PixelFormat pf = new PixelFormat(SlimDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied);

            BitmapProperties bitmapProp = new BitmapProperties()
            {
                PixelFormat = pf
            };

            result = new SlimDX.Direct2D.Bitmap(rt, new Size(sysbit.Width, sysbit.Height), dataStream, bitData.Stride, bitmapProp);

            sysbit.UnlockBits(bitData);

            return result;
        }

        public void Resize()
        {
           
        }

        public void Render()
        {
            w.BeginDraw();
            ParentGame.Draw(m_painter);
             w.EndDraw();
        }

        public override void Update(GameTime gameTime)
        {
            throw new NotImplementedException();
        }

        public void Dispose()
        {
            m_painter.Dispose();
            b.Dispose();
            w.Dispose();
            f.Dispose();
        }
    }
}
